# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,threading

from piHAlibs import (confgetval)
from .actioncmds import (actionscript)
from .corelibs import (alias2hu,huoralias,hu2alias,hudevice,lsunit)
from .parsecmds import(cmdinputf,cmdinputh)
from .servers import (INPUTq,SetupDaemons,TXControllers)

logger = logging.getLogger()

fcthuName = confgetval('pimucha.conf','RPCcmdName','fcthuName','fcthu')
phufctName = confgetval('pimucha.conf','RPCcmdName','phufctName','phufct')


RPCFunctions = []
RPCFunctions.append((lsunit, 'lsunit'))
RPCFunctions.append((actionscript,'script'))


def alias_rpc(param):
    if not param:
        return lsunit('ALIAS')
    hu = huoralias(param)
    if hu:
        if hu == param:
            return hu2alias(hu) + ' : ' + param
        else:
            return param + ' : ' + alias2hu(param)
    else:
        return 'NoAlias' + ' : ' + param
RPCFunctions.append((alias_rpc, 'alias'))


def fcthu_rpc(params):
    """
    Input : 2 parameters
    Function(on/off) HouseUnit
    HouseUnit : equivalent to device and protocol if exits
    if not, protocol default to PL
    """
    a = params.split()
    if len(a) == 2 and (a[0].lower() in ('on','off')):
        res = cmdinputf(params)
    else:
        res = rpclaunch(params)
    return res
RPCFunctions.append((fcthu_rpc, fcthuName))


def phufct_rpc(params):
    """
    Input : 3 parameters
    Protocol HouseUnit(addressId) Function(on/off)
    """
    return cmdinputh(params)
RPCFunctions.append((phufct_rpc, phufctName))


def sendto_rpc(params):
    """
    Input : 4 parameters
    Namectrl Protocol HouseUnit(addressId) Function(on/off)
    """
    a = params.split()
    if len(a) < 4:
        res = 'Input error, 4 parameters needed'
    else:
        ctrl = a[0].upper()
        if ctrl not in TXControllers:
            res = 'First parameter error, no controller with this name'
        else:
            res = cmdinputh(a[1:],a[0])
    return res
RPCFunctions.append((sendto_rpc, 'sendto'))

